import React, { Component } from 'react'
import styles from './index.module.scss'
import { Flex, PickerView } from 'antd-mobile'
import classNames from 'classnames'
import { getHouseCondition } from '../../api/filter'
import { getCurrentCity } from '../../utils/city'
import FilterFooter from '../FilterFooter'
import { Spring } from 'react-spring/renderprops'
export default class Filter extends Component {
    constructor() {
        super()
        this.state = {
            // 标题选中（决定是否高亮显示）
            selectedTypeTitle: {
                area: false,
                mode: false,
                price: false,
                more: false
            },
            // 点击或者打开类型
            openType: '',
            houseCondition: null, // 房屋筛选条件
            // 最终的数据，并且该数据将来要传递给父组件(HouseList)
            // 只有当我们点击了确定之后才能更改这个selectValue的数据，其它情况下不允许该
            // 存放选择的类型值
            selectValue: {
                area: ['area', 'null'],
                mode: ['null'],
                price: ['null'],
                more: []
            },
            // 为区域、方式、租金服务的
            tempPickerViewValue: {
                area: ['area', 'null'],
                mode: ['null'],
                price: ['null']
            },
            // 为筛选服务的
            tempMoreValue: [],
        }
    }
    types = [
        {
            type: 'area',
            name: '区域'
        },
        {
            type: 'mode',
            name: '方式'
        },
        {
            type: 'price',
            name: '租金'
        },
        {
            type: 'more',
            name: '筛选'
        }
    ]
    // 我们最终是要看 selectValue 选中的值，来决定我们的高亮状态(selectedTypeTitle)
    // 此处的约定就是 只要selectValue它的值不是默认值，那就高亮
    dealWithHighLight = () => {
        const { selectValue } = this.state
        let tempObj = {}
        Object.keys(selectValue).forEach(item => {
            // console.log(item)
            if (item === 'area') {
                tempObj['area'] =
                    selectValue.area.length > 2 && selectValue.area[1] !== 'null'
            } else if (item === 'mode') {
                tempObj['mode'] =
                    selectValue.mode.length > 0 && selectValue.mode[0] !== 'null'
            } else if (item === 'price') {
                tempObj['price'] =
                    selectValue.price.length > 0 && selectValue.price[0] !== 'null'
            } else if (item === 'more') {
                tempObj['more'] = selectValue.more.length > 0
            }
        })
        this.setState({
            selectedTypeTitle: tempObj
        })
    }
    getHouseConditionData = async () => {
        const { value } = await getCurrentCity()
        const res = await getHouseCondition(value)
        this.setState({
            houseCondition: res.data.body
        })
    }
    componentDidMount() {
        this.getHouseConditionData()
    }
    clickType = (type) => {
        const { selectedTypeTitle } = this.state
        console.log(type)
        this.setState({
            selectedTypeTitle: {
                ...selectedTypeTitle,
                [type]: true
            },
            openType: type
        })
    }
    // 类型标题部分
    renderTypeTitle = () => {
        const { selectedTypeTitle } = this.state
        return (
            <Flex className={styles.filterTitle}>
                {this.types.map(item => {
                    const isSelact = selectedTypeTitle[item.type]
                    return (
                        <Flex.Item key={item.type}>
                            <span className={classNames(styles.dropdown, { [styles.selected]: isSelact })}
                                onClick={() => { this.clickType(item.type) }}>
                                <span>{item.name}</span>
                                <i className='iconfont icon-arrow' ></i>
                            </span>
                        </Flex.Item>
                    )
                })}
            </Flex>
        )
    }
    // 渲染遮罩
    renderMask = () => {
        const { openType } = this.state
        const isShow =
            openType === 'area' || openType === 'mode' || openType === 'price' || openType === 'more'
        // if (!isShow) return null
        // return <div onClick={this.cancelMask} className={styles.mask}></div>
        return (
            <Spring to={{ opacity: isShow ? 1 : 0 }} config={{ duration: 250 }}>
                {props => {
                    if (props.opacity === 0) {
                        return null
                    }
                    return (
                        <div
                            onClick={this.cancelMask}
                            style={{ opacity: props.opacity }}
                            className={styles.mask}
                        ></div>
                    )
                }}
            </Spring>
        )
    }
    cancelMask = () => {
        this.setState({
            selectedTypeTitle: {
                [this.state.openType]: false
            }
        }, () => {
            this.setState({
                openType: ''
            }, () => {
                this.dealWithHighLight()
            })
        })
    }
    onChange = (value) => {
        const { tempPickerViewValue, openType } = this.state
        // console.log(value)
        this.setState({
            tempPickerViewValue: {
                ...tempPickerViewValue,
                [openType]: value
            }
        })
    }
    // 渲染PickerView
    renderPickerView = () => {
        const { openType, tempPickerViewValue, selectValue, houseCondition: { area, subway, rentType, price } } = this.state
        let data = null
        let cols = 3
        switch (openType) {
            case 'area':
                data = [area, subway]
                cols = 3
                break;
            case 'mode':
                data = rentType
                cols = 1
                break;
            case 'price':
                data = price
                cols = 1
                break
            default:
                break;
        }
        // 取出设置好的值，然后设置给PickerView的value即可
        const value = tempPickerViewValue[openType]
        console.log(value)
        return (
            <div>
                <PickerView
                    value={value}
                    data={data}
                    cols={cols}
                    onChange={this.onChange}
                />
                <FilterFooter onCancel={() => {
                    this.cancelMask()
                }}
                    onOk={() => {
                        this.setState({
                            selectValue: {
                                ...selectValue,
                                [openType]: tempPickerViewValue[openType]
                            }
                        }, () => {
                            this.setState({
                                openType: ''
                            }, () => {
                                // 对状态做最后一次高亮的处理
                                this.dealWithHighLight()
                                // 把我们最终的值传递给父组件
                                this.props.onConditionChange(this.state.selectValue)
                            })
                        })
                    }}
                />
            </div>
        )
    }
    // MoreView中的每一项的点击事件
    toggleSelect = (value) => {
        // console.log(value)
        let oldTempMoreValue = this.state.tempMoreValue
        if (oldTempMoreValue.includes(value)) {
            // 之前有
            oldTempMoreValue = oldTempMoreValue.filter(item => item !== value)
        } else {
            // 之前没有
            oldTempMoreValue.push(value)
        }
        this.setState({
            tempMoreValue: oldTempMoreValue
        })
    }
    // 渲染右边的MoreView中的每一项
    renderEveryItem = (title, data) => {
        const { tempMoreValue } = this.state
        return (
            <>
                <dt className={styles.dt}>{title}</dt>
                <dd className={styles.dd}>
                    {data.map(item => {
                        return <span onClick={() => this.toggleSelect(item.value)}
                            key={item.value}
                            className={classNames(styles.tag, { [styles.tagActive]: tempMoreValue.includes(item.value) })}
                        >{item.label}</span>
                    })}
                </dd>
            </>
        )
    }
    // 渲染右边的MoreView
    renderMoreView = () => {
        const {
            roomType,
            oriented,
            floor,
            characteristic
        } = this.state.houseCondition
        const { selectValue, tempMoreValue } = this.state
        return (
            <div className={styles.filterMore}>
                <div className={styles.filterMoreMask} onClick={() => this.cancelMask()}></div>
                <div className={styles.tags}>
                    <dl className={styles.dl}>
                        {/* 户型 */}
                        {this.renderEveryItem('户型', roomType)}
                        {/* 朝向 */}
                        {this.renderEveryItem('朝向', oriented)}
                        {/* 楼层 */}
                        {this.renderEveryItem('楼层', floor)}
                        {/* 房屋亮点 */}
                        {this.renderEveryItem('房屋亮点', characteristic)}
                    </dl>
                </div>
                <div className={styles.filterMoreFooter}>
                    <FilterFooter cancelText='清除' onCancel={() => { this.setState({ tempMoreValue: [] }) }}
                        onOk={() => {
                            this.setState(
                                {
                                    selectValue: { ...selectValue, more: tempMoreValue }
                                },
                                () => {
                                    this.setState(
                                        {
                                            openType: ''
                                        },
                                        () => {
                                            this.dealWithHighLight()
                                            // 把我们最终的值传递给父组件
                                            this.props.onConditionChange(this.state.selectValue)
                                        }
                                    )
                                }
                            )
                        }} />
                </div>
            </div>
        )
    }
    // 渲染PickerView
    render() {

        const { houseCondition, openType } = this.state
        return (
            <div className={styles.root}>
                {this.renderMask()}
                <div className={styles.content}>
                    {/* 渲染标题 */}
                    {this.renderTypeTitle()}
                    {/* 渲染PickerView */}
                    {houseCondition && (openType === 'area' || openType === 'mode' ||
                        openType === 'price') && this.renderPickerView()}
                    {/* 渲染右边的MoreView */}
                    {houseCondition && openType === 'more' && this.renderMoreView()}
                </div>

            </div>
        )
    }
}
